<template>
  <el-card class="good-container">
    <template #header>
      <div class="header">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增商品</el-button>
        <el-input
          v-model="search_input"
          placeholder="搜索商品"
          :style="{ width: '300px' }"
        >
          <template #prepend>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </div>
    </template>
    <el-table :data="filteredTableData" tooltip-effect="dark" style="width: 100%">
      <el-table-column prop="goodsId" label="商品编号" width="120"> </el-table-column>
      <el-table-column prop="goodsName" label="商品名" width="90"> </el-table-column>
      <el-table-column prop="goodsIntro" label="商品简介" width="180"> </el-table-column>
      <el-table-column label="商品图片" width="150px">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="$filters.prefix(scope.row.goodsCoverImg)"
          >
            <template #error>
              <div class="image-error">
                <el-icon :size="32"><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="stockNum" label="商品库存" width="90"> </el-table-column>
      <el-table-column prop="sellingPrice" label="商品售价" width="90"> </el-table-column>
      <el-table-column label="上架状态">
        <template #default="scope">
          <span style="color: green" v-if="scope.row.goodsSellStatus == 0">销售中</span>
          <span style="color: red" v-else>已下架</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button-group class="good-operate">
            <el-button type="primary" size="small" @click="handleEdit(scope.row.goodsId)"
              >修改</el-button
            >
            <el-button
              type="primary"
              size="small"
              v-if="scope.row.goodsSellStatus == 0"
              @click="handleStatus(scope.row.goodsId, 1)"
              >下架</el-button
            >
            <el-button
              type="primary"
              size="small"
              v-else
              @click="handleStatus(scope.row.goodsId, 0)"
              >上架</el-button
            >
            <el-popconfirm
              title="确定删除吗？"
              confirmButtonText="确定"
              cancelButtonText="取消"
              @confirm="handleDeleteOne(scope.row.goodsId)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="state.total"
      :page-size="state.pageSize"
      :current-page="state.currentPage"
      @current-change="changePage"
    />
  </el-card>
</template>

<script setup>
import { onMounted, reactive, getCurrentInstance, ref, computed } from "vue";
import axios from "@/utils/axios";
import { ElMessage } from "element-plus";
import { Plus, Search, Picture as IconPicture } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";

const app = getCurrentInstance();
const { goTop } = app.appContext.config.globalProperties;
const router = useRouter();
const filteredTableData = computed(() => {
  if (search_input.value === "") {
    return state.tableData; // 返回所有数据
  } else {
    const searchKeyword = search_input.value.toLowerCase(); // 将搜索关键字转为小写
    return state.tableData.filter((item) => {
      // 使用 item 中的goodsName字段和搜索关键字进行匹配
      return item.goodsName.toLowerCase().includes(searchKeyword);
    });
  }
});
const search_input = ref("");
const searchGood_f = () => {
  state.tableData = state.tableData.filter((item) => {
    return item.goodsName.includes(search_input.value);
  });
};
const handleDeleteOne = (id) => {
  axios
    .delete("/goods", {
      data: {
        ids: [id],
      },
    })
    .then(() => {
      ElMessage.success("商品删除成功");
      getGoodList();
    });
};
const searchGood = () => {
  axios
    .get("/goods/list", {
      params: {
        pageNumber: state.currentPage,
        pageSize: state.pageSize,
        goodsName: search_input.value,
      },
    })
    .then((res) => {
      state.tableData = res.list;
      state.total = res.totalCount;
      state.currentPage = res.currPage;
      state.loading = false;
      goTop && goTop();
    });
};
const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
});
onMounted(() => {
  getGoodList();
});
// 获取轮播图列表
const getGoodList = () => {
  state.loading = true;
  axios
    .get("/goods/list", {
      params: {
        pageNumber: state.currentPage,
        pageSize: state.pageSize,
      },
    })
    .then((res) => {
      state.tableData = res.list;
      state.total = res.totalCount;
      state.currentPage = res.currPage;
      state.loading = false;
      goTop && goTop();
    });
};
const handleAdd = () => {
  router.push({ path: "/add" });
};
const handleEdit = (id) => {
  router.push({ path: "/add", query: { id } });
};
const changePage = (val) => {
  state.currentPage = val;
  getGoodList();
};
const handleStatus = (id, status) => {
  axios
    .put(`/goods/status/${status}`, {
      ids: id ? [id] : [],
    })
    .then(() => {
      if (status == 1) {
        ElMessage.error("商品已下架");
      } else if (status == 0) {
        ElMessage.success("商品已上架");
      } else {
        ElMessage.error("未知错误");
      }

      getGoodList();
    });
};
</script>

<style scoped>
.good-operate {
  display: flex;
  justify-content: space-around;
}
.el-image {
  border-radius: 5px;
}
.image-error {
  width: 100px;
  height: 100px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: space-between;
}

.good-container {
  min-height: 100%;
}

.el-card.is-always-shadow {
  min-height: 100% !important;
}
</style>
